<template>
  <div class="app-container">
    <!-- <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="标题" prop="title">
        <el-input
            v-model="queryParams.title"
            placeholder="请输入"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="子标题" prop="transTitle">
        <el-input
            v-model="queryParams.transTitle"
            placeholder="请输入"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发表时间">
        <el-date-picker
            v-model="dateRange"
            style="width: 240px"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            :default-time="['00:00:00','23:59:59']"
            end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form> -->

    <el-row v-if="isAdmin" :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            @click="handleDelete(ids)"
        >删除
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">
              <el-button
                type="warning"
                plain
                icon="el-icon-download"
                size="mini"
                @click="handleExport"
              >导出
              </el-button>
            </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tableList" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column align="center" show-overflow-tooltip label="产品料号" prop="proCode" width="100"/>
      <el-table-column align="center" show-overflow-tooltip label="产品编码" prop="pno" width="160"/>
      <el-table-column align="center" show-overflow-tooltip label="产品名称" prop="pname" width="160"/>
      <el-table-column align="center" label="产品规格型号" prop="ptype" width="130"/>
      <el-table-column align="center" label="产品单位" prop="punit" width="130"/>
      <el-table-column align="center" label="产品工艺" prop="gyId" width="130"/>
      <el-table-column align="center" label="产品分类" prop="catogary" width="60"/>
      <el-table-column align="center" label="创建时间" prop="cretime" width="100"/>
      <el-table-column align="center" label="修改时间" prop="uptime" width="100"/>
      <el-table-column align="center" label="备注" prop="remark" width="300">
        <template slot-scope="{row}">
          <text-overflow :text="row.abstractStr"></text-overflow>
        </template>
      </el-table-column>
      <!-- <el-table-column align="center" label="链接" prop="url" width="160">
        <template slot-scope="{row}">
          <text-overflow :text="row.url"></text-overflow>
        </template>
      </el-table-column> -->
      <!-- <el-table-column align="center" label="英文关键字" prop="abstractStr" width="300">
        <template slot-scope="{row}">
          <text-overflow :text="row.abstractStr"></text-overflow>
        </template>
      </el-table-column> -->
      <!-- <el-table-column align="center" label="简要关键字" prop="transAbstract" width="300">
        <template slot-scope="{row}">
          <text-overflow :text="row.transAbstract"></text-overflow>
        </template>
      </el-table-column> -->
      <!-- <el-table-column align="center" label="内容概要" prop="summary" width="300">
        <template slot-scope="{row}">
          <text-overflow :text="row.summary"></text-overflow>
        </template>
      </el-table-column> -->
      <el-table-column align="center" label="操作" class-name="small-padding fixed-width" width="200" fixed="right">
        <template slot-scope="scope">
          <el-button v-if="isAdmin"
                     size="mini"
                     type="text"
                     @click="handleUpdate(scope.row)"
          >编辑
          </el-button>
       
       
      
          <el-button v-if="isAdmin"
                     size="mini"
                     type="text"
                     @click="handleDelete([scope.row.id])"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.curPage"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="70%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" inline>
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入"/>
        </el-form-item>
        <el-form-item label="爬取日期" prop="scrapeDate">
          <el-date-picker v-model="form.scrapeDate" value-format="yyyy-MM-dd" type="date" placeholder="选择日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="发表日期" prop="publishDate">
          <el-date-picker v-model="form.publishDate" value-format="yyyy-MM-dd" type="date" placeholder="选择日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="子标题" prop="transTitle">
          <el-input v-model="form.transTitle" placeholder="请输入"/>
        </el-form-item>
        <el-form-item label="关键字" prop="keyword">
          <el-input v-model="form.keyword" placeholder="请输入"/>
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="form.author" placeholder="请输入"/>
        </el-form-item>
        <el-form-item label="语言" prop="language">
          <el-input v-model="form.language" placeholder="请输入"/>
        </el-form-item>
        <el-form-item label="类型" prop="typeTag">
          <el-input v-model="form.typeTag" placeholder="请输入"/>
        </el-form-item>
        <el-form-item label="链接" prop="url">
          <el-input v-model="form.url" placeholder="请输入"/>
        </el-form-item>
        <el-form-item label="英文关键字" prop="abstractStr">
          <el-input v-model="form.abstractStr" placeholder="请输入"/>
        </el-form-item>
        <el-form-item label="简要关键字" prop="transAbstract">
          <el-input v-model="form.transAbstract" placeholder="请输入"/>
        </el-form-item>
        <!-- <el-form-item label="" prop="fwb">
          <div style="border: 1px solid #ccc;">
            <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editor"
                :defaultConfig="toolbarConfig"
                :mode="mode"
            />
            <Editor
                style="height: 300px; overflow-y: hidden;"
                v-model="form.fwb"
                :defaultConfig="editorConfig"
                :mode="mode"
                @onCreated="onCreated"
            />
          </div>

        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 文件预览弹窗 -->
    <el-dialog
        title="在线预览"
        :visible.sync="previewVisible"
        width="60%"
    >
      <vue-office-docx :src="previewUrl" @rendered="rendered"/>
    </el-dialog>

  </div>

</template>

<script>
import { changeRoleStatus, deptTreeSelect } from '@/api/system/role'
import { roleMenuTreeselect } from '@/api/system/menu'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { DomEditor } from '@wangeditor/editor'
import VueOfficeDocx from '@vue-office/docx'
import '@vue-office/docx/lib/index.css'
import TextOverflow from '@/views/qyxx/components/text-overflow.vue'
import { createQyxx, deleteQyxx, editQyxx, getQyxxList, getSourcePath,pageProduct } from '@/api'
import { mapGetters } from 'vuex'

export default {
  name: 'dp',
  components: { TextOverflow, Editor, Toolbar, VueOfficeDocx },
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      tableList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      deptExpand: true,
      deptNodeAll: false,
      // 日期范围
      dateRange: [],
      // 数据范围选项
      dataScopeOptions: [
        {
          value: '1',
          label: '全部数据权限'
        },
        {
          value: '2',
          label: '自定数据权限'
        },
        {
          value: '3',
          label: '本部门数据权限'
        },
        {
          value: '4',
          label: '本部门及以下数据权限'
        },
        {
          value: '5',
          label: '仅本人数据权限'
        }
      ],
      // 文件预览
      previewUrl: '',
      // 弹出层是否可见
      previewVisible: false,
      // 菜单列表
      menuOptions: [],
      // 部门列表
      deptOptions: [],
      // 查询参数
      queryParams: {
        curPage: 1,
        pageSize: 10,
        title: undefined,
        transTitle: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 表单校验
      rules: {
        title: [
          { required: true, message: '标题不能为空', trigger: 'blur' }
        ],
        scrapeDate: [
          { required: true, message: '爬取日期不能为空', trigger: 'blur' }
        ],
        publishDate: [
          { required: true, message: '发表日期不能为空', trigger: 'blur' }
        ],
        transTitle: [
          { required: true, message: '子标题不能为空', trigger: 'blur' }
        ],
        keyword: [
          { required: true, message: '关键字不能为空', trigger: 'blur' }
          ],
        author: [
          { required: true, message: '作者不能为空', trigger: 'blur' }
        ],
        language: [
          { required: true, message: '语言不能为空', trigger: 'blur' }
        ],
        typeTag: [
          { required: true, message: '类型不能为空', trigger: 'blur' }
        ],
        url: [
          { required: true, message: '链接不能为空', trigger: 'blur' }
        ],
        abstractStr: [
          { required: true, message: '英文关键字不能为空', trigger: 'blur' }
        ],
        transAbstract: [
          { required: true, message: '简要关键字不能为空', trigger: 'blur' }
        ],
        fwb: [
          { required: true, message: '内容不能为空', trigger: 'blur' }
        ],
        enclosure: [
          { required: true, message: '权限字符不能为空', trigger: 'blur' }
        ],
        listenFileTypeCode: [
          { required: true, message: '权限字符不能为空', trigger: 'blur' }
        ]
      },
      editor: null,
      toolbarConfig: { excludeKeys: ['emotion', 'insertLink', 'group-image', 'group-video'] },
      editorConfig: { placeholder: '请输入内容...' },
      mode: 'default', // or 'simple'
      classifyId: this.$route.query.id,
      selectTableList: [],
      ids: []
    }
  },

  computed: { ...mapGetters(['isAdmin']) },
  created() {
    this.getList()
  },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  },
  methods: {
    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
      // console.log(this.editor.getAllMenuKeys())
      const toolbar = DomEditor.getToolbar(this.editor)
      // console.log(DomEditor, this)
    },
    /** 查询角色列表 */
    getList() {
       this.loading = true
      // getQyxxList({
      //   classifyId: this.classifyId,
      //   deleteData: 0,
      //   ...this.queryParams,
      //   publishStartTime: this.dateRange && this.dateRange[0],
      //   publishEndTime: this.dateRange && this.dateRange[1]
      // }).then(res => {
      //   this.tableList = res.data.records
      //   this.total = res.data.total
      // }).finally(() => {
      //   this.loading = false
      // })
      pageProduct(this.queryParams.curPage,this.queryParams.pageSize).then(res=>{
        console.log(res)
        this.tableList = res.data.records
        this.total = res.data.total
      }).finally(()=>{
        this.loading = false
      })
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys()
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys()
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
      return checkedKeys
    },
    // 所有部门节点数据
    getDeptAllCheckedKeys() {
      // 目前被选中的部门节点
      let checkedKeys = this.$refs.dept.getCheckedKeys()
      // 半选中的部门节点
      let halfCheckedKeys = this.$refs.dept.getHalfCheckedKeys()
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
      return checkedKeys
    },
    /** 根据角色ID查询菜单树结构 */
    getRoleMenuTreeselect(roleId) {
      return roleMenuTreeselect(roleId).then(response => {
        this.menuOptions = response.menus
        return response
      })
    },
    /** 根据角色ID查询部门树结构 */
    getDeptTree(roleId) {
      return deptTreeSelect(roleId).then(response => {
        this.deptOptions = response.depts
        return response
      })
    },
    // 角色状态修改
    handleStatusChange(row) {
      let text = row.status === '0' ? '启用' : '停用'
      this.$modal.confirm('确认要"' + text + '""' + row.title + '"角色吗？').then(function() {
        return changeRoleStatus(row.roleId, row.status)
      }).then(() => {
        this.$modal.msgSuccess(text + '成功')
      }).catch(function() {
        row.status = row.status === '0' ? '1' : '0'
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 取消按钮（数据权限）
    cancelDataScope() {
      this.openDataScope = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        title: undefined,
        scrapeDate: undefined,
        publishDate: undefined,
        transTitle: undefined,
        keyword: undefined,
        author: undefined,
        language: undefined,
        typeTag: undefined,
        url: undefined,
        abstractStr: undefined,
        transAbstract: undefined,
        fwb: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.curPage = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selectTableList = selection
      this.ids = selection.map(item => item.id)
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.title = '修改'
      this.open = true
      this.form = { ...row }
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          let params = { ...this.form, classifyId: this.classifyId, listenFileTypeCode: 1 }
          let formData = new FormData()
          for (let key in params) {
            if (params[key] !== void 0) {
              formData.append(key, params[key])
            }
          }
          if (this.form.id) {
            editQyxx(formData).then(res => {
              this.open = false
              this.getList()
            })
          } else {
            createQyxx(formData).then(res => {
              this.open = false
              this.getList()
            })
          }
          this.open = false
        }
      })
    },
    /** 获取附件链接 */
    getEnclosureUrl(row) {
      getSourcePath({ id: row.id }).then(response => {
        this.previewUrl = response.data[0]
      }).catch(error => {
        console.log(error)
      })
    },
    /** 预览按钮操作 */
    handlePreview(row) {
      this.previewVisible = true
      this.previewUrl = ''
      this.getEnclosureUrl(row)
    },
    rendered() {
      console.log('渲染完成')
      console.log(this.previewUrl)
    },
    /** 下载文件 */
    downloadFile() {
      const aLink = document.createElement('a')
      aLink.href = this.previewUrl
      aLink.click()
    },
    handleDownload(row) {
      this.getEnclosureUrl(row)
      setTimeout(() => {
        this.downloadFile()
      }, 1000)
    },
    handleDownload2(row) {
      // 2. 创建Blob对象，类型为纯文本
      const blob = new Blob([row.summary], { type: 'application/msword;charset=utf-8' })

      // 3. 使用file-saver库的saveAs函数触发下载
      saveAs(blob, row.title + '.doc')
    },
    /** 收藏按钮操作 */
    handleCollection() {
      // TODO 收藏功能
    },

    /** 删除按钮操作 */
    handleDelete(ids) {
      this.$modal.confirm('是否确认删除？').then(() => {
        deleteQyxx(ids).then(res => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/role/export', {
        ...this.queryParams
      }, `role_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style lang="scss">
.el-tooltip__popper {
  background-color: #fff !important;
  color: #606266 !important;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1) !important;
  max-width: 600px;
}

/*
.el-table .cell.el-tooltip {
  overflow: hidden;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 5;
  display: -moz-box;
  -moz-box-orient: vertical;
  -moz-line-clamp: 5;
  word-break: break-all;
  white-space: normal;
}*/
</style>
